package br.com.pentagrama.util;

import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.ParseException;

public class NumberUtil {

	private static DecimalFormat df = new DecimalFormat();

	static {
		DecimalFormatSymbols symbols = new DecimalFormatSymbols();
		symbols.setDecimalSeparator(',');
		symbols.setGroupingSeparator('.');
		df.setDecimalFormatSymbols(symbols);
		df.setDecimalSeparatorAlwaysShown(true);
		df.setRoundingMode(RoundingMode.HALF_EVEN);
	}

	public static String formatDecimal(Double decimal) {
		return formatDecimal(decimal, 2);
	}

	public static String formatDecimal(Double decimal, int decimais) {
		if (decimal == null) {
			return "";
		}
		df.setMinimumFractionDigits(decimais);
		df.setMaximumFractionDigits(decimais);
		return df.format(decimal);
	}

	public static Double round(Double decimal) {
		return round(decimal, 2);
	}

	public static Double round(Double decimal, int decimais) {
		if (decimal == null) {
			return null;
		}
		String fmt = formatDecimal(decimal, decimais);
		try {
			return Double.valueOf(df.parse(fmt).doubleValue());
		} catch (ParseException e) {
			e.printStackTrace();
			return decimal;
		}
	}

	public static boolean isInt(String number) {
		try {
			Integer.parseInt(number);
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	public static boolean isDouble(String number) {
		try {
			Double.parseDouble(number);
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	public static Integer toInt(Object objeto) {
		return Integer.parseInt(objeto.toString());
	}

	public static Integer toInt(String texto) {
		return Integer.parseInt(texto);
	}

}
